

# 模拟Meter 模式

import serial
import math
from time import sleep
import xlrd
import time
import sys
import winsound
import datetime
from DataConvert.DataConvert import *
from Uart.SerialHelper import *
import logging
import logging.config
from os import path
config_log='../LogConfig/logger.conf'
from Iec21 import *

import threading

#a=[b'/', b'H', b'L', b'Y', 0x20, b'5', 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, b'V', 0x20,b'1', b'.', b'0', 0x0D, 0x0A]
ack=b'/HLY5'+str2hexs('0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20')+b'V\x201.0\r\n'
ack=b'/HLY'+str2hexs('0x34,0x5C,0x34,0x0D,0x0A')

#ack=b'/HLY\x205'+b'V\x201.0'


class Iec21_M(SerialHelper):

    def __init__(self,port='com1',bps_before='4800',ByteSize="8", Parity="N", Stopbits="1",
                 bps_after='9600',bps_change=True,password='00000000',wait=1.5):

        SerialHelper.__init__(self,Port=port, BaudRate=bps_before,ByteSize=ByteSize,Parity=Parity,Stopbits=Stopbits,wait=wait)

        self.bps_change=bps_change
        self.bps_after=bps_after
        self.password=password
        self._serial = None
        self._is_connected = False

        self.iec_sta_idle='iec_sta_idle'
        self.iec_sta_hand='iec_sta_hand'
        self.iec_sta_passwordcheck='iec_sta_passwordcheck'
        self.iec_sta_bpschange='iec_sta_bpschange'
        self.iec_sta_wr='iec_sta_wr'
        self.iec_sta_err='self.iec_sta_err'

        self.iecsta=self.iec_sta_idle

        logging.config.fileConfig(config_log)
        self.Log_Iec21_M=logging.getLogger("iec21")



        self.senddata='test'

    def send(self,buf,msg=None):
        if msg is not None:
            self.Log_Iec21_M.info(msg)
        self.write(buf)
    def receive(self,msg=None):
        data=self.readall()
        if(data):
            if msg is not None:
                self.Log_Iec21_M.info(msg)
        return data

    def change(self, ):
        temp=''
        while 1:
            print("请输入readout 输出数据：连续两个空格结束")

            a = input()
            temp+=(a+'\r\n')
            if(len(a)>2):
                if str(a[-2:])=='  ':
                    self.senddata=temp
                    print("-----------------数据接收完成了--------------------",)
                    print("readout data is ",(temp))
                    temp=''


    def readout(self,senddata=None):
        self.iecsta = self.iec_sta_idle
        if(senddata!=None):
            self.senddata=senddata
        while 1:
            uart_get = self.receive()
            if len(uart_get):

                uart_get = bytearray(uart_get)
                for i in range(len(uart_get)):
                    uart_get[i] &= 0x7f

                if len(uart_get) >= 2:
                    if uart_get[0:2] == b'\x37\x37':
                        uart_get = uart_get[2:]
                        self.iecsta = self.iec_sta_idle
                        continue

                uart_get = bytearray(uart_get)
                for i in range(len(uart_get)):
                    uart_get[i] &= 0x7f

                if(1):
                #if self.iecsta == self.iec_sta_idle:
                    if uart_get[:3] == b'/?!' and uart_get[-2:] == b'\r\n':
                        buf = ack#str2bytes("/HLY") + str2hexs('34 5C 34 0D 0A ')
                        self.send(buf)
                        self.iecsta = self.iec_sta_hand
                        continue

                if self.iecsta == self.iec_sta_hand:
                    # bps change
                    if int(uart_get[2]) >= 0 and int(uart_get[2]) <= 6:
                        self.bps_after = str(300 * (2 ** int(uart_get[2] - 0x30)))
                        self._serial.baudrate = str(self.bps_after)
                    buf = b'\x02' + str2bytes(self.senddata)
                    buf = buf + b'!\r\n\x03'  # ! CR LF ETX BCC
                    checknum = bcc(buf[1:])
                    buf += bytes((checknum,))
                    self.send(buf)


if __name__ == '__main__':

    a=input("com=\r\n")
    u=Iec21_M(port=a,bps_before='300',bps_after='4800',wait=0.2)
    u.connect()
    u.senddata="1.8.0(000000.06*kWh)\r\n"+ \
               "1.8.1(000000.06*kWh)\r\n"+ \
               "1.8.1(000000.01*kWh)\r\n"+ \
               "1.8.2(000000.02*kWh)\r\n" + \
               "1.8.3(000000.03*kWh)\r\n" + \
               "1.8.4(000000.06*kWh)\r\n" + \
               "3.8.0(000000.06*kWh)\r\n" + \
               "3.8.1(000000.06*kWh)\r\n" + \
               "3.8.2(000000.03*kWh)\r\n" + \
               "3.8.3(000000.05*kWh)\r\n" + \
               "3.8.4(000000.06*kWh)\r\n" + \
               "1.6.0(000.000*kW)\r\n"    + \
               "3.6.0(000.000*kvar)\r\n"  + \
               "C.1.0(123456789012)\r\n"

    # u.senddata="1.8.0(00000000.53kWh)\r\n"+ \
    #            "1.8.1(00000000.51kWh)\r\n"+ \
    #            "1.8.2(00000000.52kWh)\r\n" + \
    #            "1.8.3(00000000.52kWh)\r\n" + \
    #            "1.8.4(00000009.39kWh)\r\n"


    t2 = threading.Thread(target=u.change, name='change')
    t1 = threading.Thread(target=u.readout, name='readout')
    t1.start()
    t2.start()


